package com.handong.handserialprogram.broadcastreceiver;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.util.Log;

import com.google.gson.Gson;
import com.handong.handserialprogram.module.serialport.SerialPortUtil;

import java.util.ArrayList;
import java.util.List;

import static android.content.pm.PackageManager.GET_ACTIVITIES;

/**
 * Created by userKey on 2017/4/20.
 */

public class BootBroadCastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("handong", "BootBroadCastReceiver receive broadcast.");
        //MainActivity就是开机显示的界面
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {

            if (!isLauncherRunnig(context)) {
                context.startActivity(context.getPackageManager().getLaunchIntentForPackage("com.handong.handserialprogram"));
                Log.d("handong", "getPackageManager().getLaunchIntentForPackage");
            }


            //Intent bootIntent = new Intent(context, TaskListActivity.class);
            //bootIntent.addFlags(intent.FLAG_ACTIVITY_NEW_TASK);
            //context.startActivity(bootIntent);
        }

        Log.d("handong", "Intent.ACTION_BOOT_COMPLETED");
    }

    private boolean isLauncherRunnig(Context context) {
        boolean result = false;
        //List<String> names = getAllTheLauncher(context);
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appList = mActivityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo running : appList) {
            if (running.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                //for (int i = 0; i < names.size(); i++) {
                Log.d("running", running.processName);
                    if ("com.handong.handserialprogram".equals(running.processName)) {
                        return true;
                    }
                //}
            }
        }
        return false;
    }

}
